const express = require("express");
const app = express();
const webpackDevMiddleware = require("webpack-dev-middleware");
const webpackHotMiddleware = require("webpack-hot-middleware");
const config = require("../build/config");
const path = require("path");

const webpack = require("webpack");
const webpackConfig = require("../build/webpack.dev");

const webpackCompiler = webpack(webpackConfig);

app.use(webpackDevMiddleware(webpackCompiler, {
    publicPath:  config.publicPath
}));
app.use(webpackHotMiddleware(webpackCompiler));


app.use("/static",express.static(path.join(__dirname, "../dist/static")));

app.use("/api",require("./index"));

app.use("/admin**",(req, res, next) =>{

    const filename = path.join("./dist", "admin.html");

    webpackCompiler.outputFileSystem.readFile(filename, (err, result) =>{
        if (err){
            return next(err);
        }
        res.set("content-type", "text/html");
        res.send(result);
        res.end();
    });
});


app.use("/**",(req, res, next) =>{

    const filename = path.join("./dist", "client.html");

    webpackCompiler.outputFileSystem.readFile(filename, (err, result) =>{
        if (err){
            return next(err);
        }
        res.set("content-type", "text/html");
        res.send(result);
        res.end();
    });
});


app.listen(config.port, function () {
    console.log(`app listening on port ${config.port}!`);
});


